package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author gakki
 * @create 2022/5/1 21:35
 */
@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {
    /**
     * 数据库异常处理
     * @param exception
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
        //日志输出
        log.error(exception.getMessage());

        //判断error类型
        if (exception.getMessage().contains("Duplicate entry")) {
            log.info("going");
            String[] strs = exception.getMessage().split(" ");
            String msg = strs[2].substring(1, strs[2].length()-1) + "用户名已存在！";
            return Result.error(msg);
        }
        return Result.error("未知错误！");
    }

    /**
     * 自定义异常处理
     * @param exception
     */
    @ExceptionHandler(CustomException.class)
    public Result<String> customExceptioHandler(CustomException exception) {
        //日志输出
        log.error(exception.getMessage());
        return Result.error(exception.getMessage());
    }
}
